package com.xzq.httptest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Response;
import okhttp3.ResponseBody;

public class MainActivity extends AppCompatActivity {

    private Handler handler;
    private TextView textView;
    private UserBean bean;

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.token);

        SharedPreferences sharedPreferences = getSharedPreferences("userToken", Context.MODE_PRIVATE);
        String token = sharedPreferences.getString("token", null);
        if (token != null) {
            String url = "http://api.myas.maissy.net/api/api_user/user/show";
            loadData(token, url);
        }

        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 1) {
                    bean = (UserBean) msg.obj;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textView.setText(bean.getData().getUsername());
                        }
                    });
                }
            }
        };

    }

    private void loadData(String token, String url) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    Response response = HttpUtil.get(url, token);
                    String bodyTxt = response.body().string();
                    LogUtils.i(bodyTxt);
                    UserBean bean = new Gson().fromJson(bodyTxt, UserBean.class);
                    Message message = new Message();
                    message.what = 1;
                    message.obj = bean;
                    handler.handleMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();
    }
}